package com.badibadi.mail;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.badibadi.activity.BaseActivity;
import com.badibadi.activity.SelectPictsMail_Activity;
import com.badibadi.activity.ShowViewPagerActivity;
import com.badibadi.adapter.Gridview3Adapter;
import com.badibadi.infos.Img;
import com.badibadi.mail.MailActivity.MySpSizeAdapter;
import com.badibadi.mytools.CommonUtils;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.DisplayUtil;
import com.badibadi.mytools.ImageTools;
import com.badibadi.mytools.SinaExpressionTools;
import com.badibadi.mytools.Utils;
import com.badibadi.mytools.XUtils;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.SinaExpressionActivity;
import com.badibadi.uniclubber.R.id;
import com.badibadi.uniclubber.R.string;
import com.libjph.util.StringUtil;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

/**
 * (俱乐部管理员)群发站内信 (它的直接子类有MailLianXiClubGLYActivity) 2014-10-16
 * 
 * @author Administrator activity_mail_send
 * 
 *         TextView text = new TextView(context);//粗体 mail_xie_zhi
 *         text.getPaint().setFakeBoldText(true); activity_mail_send
 */
public class MailSendAMassMailActivity extends BaseActivity implements
		OnClickListener {

	private static final int BiaoQing = 8081;
	private ImageButton btn_textSize_Setting, btn_chuxi, btn_xiezhi,
			btn_xiahuaxian, btn_biaoqin, btn_paizhao, btn_movies;
	private Intent intent = null;
	private String[] ssp = { "5", "10", "15", "20", "25", "30", "35", "40",
			"45", "50" };
	protected EditText activity_mail_content, et_zhuzhi;
	protected TextView activity_mail_send, title_mail, clubAllPeople;
	protected ImageView activity_mail_titalimg;
	ListView lv;// 文字大小列表
	// 需要传过来的数据
	public String cid, admin_uid, clubname;

	AlertDialog textdialog;
	/**
	 * 加粗 TextView tv = (TextView)findViewById(R.id.TextView01); TextPaint tp =
	 * tv.getPaint(); tp.setFakeBoldText(true);
	 * 
	 * login_registration.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //添加线
	 * //login_edit_username.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
	 * //删除线
	 */
	/**
	 * 是否是粗体
	 */
	private boolean isChuti = false;
	/**
	 * 是否是斜体
	 */
	private boolean isXieti = false;
	/**
	 * 是否有下划线
	 */
	private boolean hasXiahuaxian = false;

	// 下面的是照相机的
	private ArrayList<String> pathlist;
	private GridView picGridView;
	ArrayList<Img> imgs;
	Gridview3Adapter picGridView_adapter;
	ArrayList<String> htmp_list;

	public Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(MailSendAMassMailActivity.this);
				try {
					Utils.showMessage(MailSendAMassMailActivity.this, getResources().getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 2:
				Utils.ExitPrgress(MailSendAMassMailActivity.this);
				try {
					Utils.showMessage(MailSendAMassMailActivity.this, getResources().getString(R.string.l_xb91));
					finish();
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 3:
				Utils.ExitPrgress(MailSendAMassMailActivity.this);
				try {
					Utils.showMessage(MailSendAMassMailActivity.this, getResources().getString(R.string.l_xb92));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 4:
				Utils.ExitPrgress(MailSendAMassMailActivity.this);
				try {
					Utils.showMessage(MailSendAMassMailActivity.this, getResources().getString(R.string.l_xb92));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 2000:
				Utils.ExitPrgress(MailSendAMassMailActivity.this);
				Utils.ExitProgress_hen(MailSendAMassMailActivity.this);
				Utils.showMessage(MailSendAMassMailActivity.this, getResources().getString(R.string.l_xb18));
				String temp_path = msg.getData().getString("path");
				htmp_list=new ArrayList<String>();
				htmp_list = fenge(temp_path);
			
				for (int i = 0; i < htmp_list.size(); i++) {
//					activity_mail_content.setText(activity_mail_content
//							.getText().toString() + list3.get(i));
//					activity_mail_content.setSelection(activity_mail_content
//							.getText().toString().length());
					Img img=new Img();
					String cc=htmp_list.get(i).substring(10, htmp_list.get(i).length()-4);
					img.setPath(cc);
					imgs.add(img);
				}
				picGridView_adapter.notifyDataSetChanged();
				

				
				break;
			default:
				break;
			}
		}

	};

	private ArrayList<String> fenge(String ds) {
		String dg[] = ds.split(",");
		ArrayList<String> list2 = new ArrayList<String>();
		if (dg != null) {
			for (int i = 0; i < dg.length; i++) {
				// <img
				// src='http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/7a/shenshou_thumb.gif'
				// />"
				if (dg[i].startsWith("http")) {
					list2.add("<img src='" + dg[i] + "' />");
				} else {
					list2.add("<img src='" + Constants.BadiDownImgUrl + dg[i]
							+ "' />");
				}
			}
		}
		return list2;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.sendamassmail);
		int test = MailActivity.ALLMAIL;
		this.findViewById(R.id.return_btn).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						finish();
					}
				});
		init();

	}

	public void init() {
		// TODO Auto-generated method stub

		cid = getIntent().getStringExtra("cid");
		admin_uid = getIntent().getStringExtra("admin_uid");

		clubname = getIntent().getStringExtra("clubname");

		picGridView = (GridView) this.findViewById(R.id.picture_GridView);
		picGridView.setHorizontalSpacing(DisplayUtil.dip2px(
				MailSendAMassMailActivity.this, 5));
		picGridView.setVerticalSpacing(DisplayUtil.dip2px(
				MailSendAMassMailActivity.this, 5));
		imgs = new ArrayList<Img>();

		picGridView_adapter = new Gridview3Adapter(
				MailSendAMassMailActivity.this, imgs);
		picGridView.setAdapter(picGridView_adapter);
		picGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MailSendAMassMailActivity.this,
						ShowViewPagerActivity.class);
				intent.putStringArrayListExtra("pic",
						(ArrayList<String>) picGridView_adapter.getSList());
				intent.putExtra("position", position);
				startActivity(intent);
			}
		});
		pathlist = new ArrayList<String>();

		et_zhuzhi = (EditText) this.findViewById(R.id.et_zhuzhi);

		clubAllPeople = (TextView) this.findViewById(R.id.clubAllPeople);
		clubAllPeople.setText("" + clubname + getResources().getString(R.string.l_xb93));

		btn_textSize_Setting = (ImageButton) this
				.findViewById(R.id.mail_textSize_Setting);
		btn_textSize_Setting.setOnClickListener(MailSendAMassMailActivity.this);
		btn_chuxi = (ImageButton) this.findViewById(R.id.mail_chuxi);
		btn_chuxi.setOnClickListener(MailSendAMassMailActivity.this);
		btn_xiezhi = (ImageButton) findViewById(R.id.mail_xie_zhi);
		btn_xiezhi.setOnClickListener(this);
		btn_xiahuaxian=(ImageButton)this.findViewById(R.id.mail_xiahuaxian);
		btn_xiahuaxian.setOnClickListener(this);

		activity_mail_content = (EditText) findViewById(R.id.activity_mail_content);
		activity_mail_send = (TextView) findViewById(R.id.activity_mail_send);
		activity_mail_send.setOnClickListener(MailSendAMassMailActivity.this);
		activity_mail_titalimg = (ImageView) findViewById(R.id.activity_mail_titalimg);
		title_mail = (TextView) findViewById(R.id.title_mail);
		

		pathlist = new ArrayList<String>();
		btn_paizhao = (ImageButton) findViewById(R.id.mail_paizhao);
		btn_paizhao.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MailSendAMassMailActivity.this,
						SelectPictsMail_Activity.class);
				intent.putExtra("panduan", "no_set");
				startActivityForResult(intent, 3);
			}
		});
		this.findViewById(R.id.mail_biaoqing).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.mail_xie_zhi:
			ChangeXieti();
			break;
		case R.id.mail_textSize_Setting:
			initDialog();
			break;
		case R.id.mail_chuxi:
			ChangeChuti();
			// if (isChuti) {
			// isChuti = false;
			// } else {
			// isChuti = true;
			// }
			break;
		case R.id.mail_xiahuaxian:
			ChangeXiaHuaXian();
			break;
		case R.id.mail_biaoqing:
			Intent intent = new Intent(MailSendAMassMailActivity.this,
					SinaExpressionActivity.class);
			startActivityForResult(intent, BiaoQing);
			break;
		case R.id.activity_mail_send:// 发送

			String content = activity_mail_content.getText().toString().trim();
			if (!StringUtil.isNullOrEmpty(content)) {
				StringBuffer buff = new StringBuffer(content);
				if (imgs != null && !imgs.isEmpty())
				{
					buff.append("<div>");
					for (int i = 0; i < imgs.size(); i++) {
						
						
						buff.append(Utils.toMailHtmL(imgs.get(i).getPath()));
//						   
					}
					buff.append("<div style='clear:both;'></div></div>");
				}
				String content3 = buff.toString().trim();
//				   
				String content2 = SinaExpressionTools
						.replaceAllReplaceToPath(content3);
				content2=content2.replaceAll("\\[", "");
				content2=content2.replaceAll("\\]", "");
//				String content3 = buff.toString();
//
//				String content2 = SinaExpressionTools
//						.replaceAllReplaceToPath(content3);
				sendMessage(content2);
			} else {
				Utils.showMessage(MailSendAMassMailActivity.this,getResources().getString(R.string.l_xb21));
			}

			break;
		}
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub

		if (arg0 == BiaoQing
				&& arg1 == SinaExpressionActivity.ACTIVITY_BIAOQING) {
			if (arg2 != null) {
				String con1 = activity_mail_content.getText().toString();
				String con2 = arg2.getStringExtra("result");
				activity_mail_content.setText(con1 + con2);
				activity_mail_content.setSelection((con1 + con2).length());
			}

		}
		if (arg0 == 3 && arg1 == SelectPictsMail_Activity.HUICHUAN_KEY_1) {
			if (arg2 != null) {
				pathlist = arg2.getStringArrayListExtra("files");
//                Utils.showMessage(MailSendAMassMailActivity.this, getResources().getString(R.string.l_xb46));
				XUtils.UpImg_ceshi_douhaoXUtils(pathlist,
						MailSendAMassMailActivity.this, handler);
			}
		}

		super.onActivityResult(arg0, arg1, arg2);
	}

	private void initDialog() {
		lv = new ListView(MailSendAMassMailActivity.this);
		// lv.setChoiceMode(choiceMode);
		// ArrayAdapter<Integer> arr=new
		// ArrayAdapter<Integer>(getApplicationContext(), resource,
		// textViewResourceId, objects)
		final MySpSizeAdapter spAdapter = new MySpSizeAdapter();
		lv.setAdapter(spAdapter);
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				setTextSize(Float.parseFloat((String) spAdapter
						.getItem(position)));
				if (textdialog != null) {
					textdialog.dismiss();
				}

			}
		});
		textdialog = new AlertDialog.Builder(MailSendAMassMailActivity.this)
				.setTitle(getResources().getString(R.string.l_xb90)).setView(lv).show();
	}

	/**
	 * 设置字体大小
	 * 
	 * @param content
	 */
	private void setTextSize(Float content) {
		activity_mail_content.setTextSize(content);
	}

	/**
	 * 设置粗体和取消粗体
	 */
	private void ChangeChuti() {
		if (isChuti == false) {
			SpannableString msp = new SpannableString(activity_mail_content
					.getText().toString().trim());
			msp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0,
					msp.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 粗体
			// activity_mail_content.
			// activity_mail_content.getPaint().setFakeBoldText(true);

			activity_mail_content.setText(msp);
			activity_mail_content.setSelection(msp.length());
			isChuti = true;
		} else {
			SpannableString msp = new SpannableString(activity_mail_content
					.getText().toString().trim());
			msp.setSpan(new StyleSpan(android.graphics.Typeface.NORMAL), 0,
					msp.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 正常
			// activity_mail_content.
			// activity_mail_content.getPaint().setFakeBoldText(true);

			activity_mail_content.setText(msp);
			activity_mail_content.setSelection(msp.length());
			isChuti = false;
		}
		hasXiahuaxian=false;
		isXieti=false;
	}

	/**
	 * 设置字体下划线
	 */
	private void ChangeXiaHuaXian() {
		if (hasXiahuaxian == false) {
			SpannableString msp = new SpannableString(activity_mail_content
					.getText().toString().trim());
			msp.setSpan(new UnderlineSpan(), 0, msp.length(),
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			// activity_mail_content.
			// activity_mail_content.getPaint().setFakeBoldText(true);

			activity_mail_content.setText(msp);
			activity_mail_content.setSelection(msp.length());
			hasXiahuaxian = true;
		} else {
			SpannableString msp = new SpannableString(activity_mail_content
					.getText().toString().trim());
			msp.setSpan(new StyleSpan(android.graphics.Typeface.NORMAL), 0,
					msp.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 正常
			// activity_mail_content.getPaint().setFakeBoldText(false);
			activity_mail_content.setText(msp);
			activity_mail_content.setSelection(msp.length());
			hasXiahuaxian = false;
		}

		isChuti=false;
			isXieti=false;
	}

	/**
	 * 设置斜体和取消斜体
	 */
	private void ChangeXieti() {
		if (isXieti == false) {
			SpannableString msp = new SpannableString(activity_mail_content
					.getText().toString().trim());
			msp.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0,
					msp.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 斜体
			// activity_mail_content.
			// activity_mail_content.getPaint().setFakeBoldText(true);

			activity_mail_content.setText(msp);
			activity_mail_content.setSelection(msp.length());
			isXieti = true;
		} else {
			SpannableString msp = new SpannableString(activity_mail_content
					.getText().toString().trim());
			msp.setSpan(new StyleSpan(android.graphics.Typeface.NORMAL), 0,
					msp.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 正常
			// activity_mail_content.getPaint().setFakeBoldText(false);
			activity_mail_content.setText(msp);
			activity_mail_content.setSelection(msp.length());
			isXieti = false;
		}
		isChuti=false;
		hasXiahuaxian=false;

	}

	public class MySpSizeAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return ssp.length;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return ssp[position];
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub

			LayoutInflater inflater = LayoutInflater
					.from(MailSendAMassMailActivity.this);
			convertView = inflater
					.inflate(R.layout.mail_sp_import_layout, null);

			TextView tv = (TextView) convertView
					.findViewById(R.id.mail_import_sp);
			tv.setText("" + ssp[position]);
			tv.setTextSize(Integer.parseInt(ssp[position]));
			// Typeface face=Typeface.createFromAsset(getAssets(),
			// "founts/cukaitijian.ttf");
			// tv.setTypeface(face);
			// Paint p=new Paint();
			// p.setTextSkewX(-1);
			return convertView;
		}
	}

	/**
	 * 发送俱乐部通知
	 */
	protected void sendMessage(String content2) {
		clubNotice(cid, admin_uid, et_zhuzhi.getText().toString(), content2);
	}

	/**
	 * 站内信之---俱乐部通知（群发消息）----post $cid //俱乐部ID $uid //俱乐部管理员ID $title //群消息标题
	 * $content //群消息内容
	 */
	public void clubNotice(String cid, String admin_uid, String title,
			String content) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cid", cid);
		map.put("uid", admin_uid);
		map.put("title", title);
		String con = SinaExpressionTools.replaceAllReplaceToPath(content);
		map.put("content", con);
		CommonUtils.CommomPostfunction(MailSendAMassMailActivity.this,
				Constants.BadiUrl_1 + "commonality/clubNotice", map, handler,
				1, 3, 2, 4);
	}

}
